﻿using HtmlAgilityPack;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;

namespace NGPOTD
{
    class Program
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        private const string folderName = "NationalGeographic";
        private const int SPI_SETDESKWALLPAPER = 20;
        private const int SPIF_UPDATEINIFILE = 0x01;

        static void Main(string[] args)
        {
            try
            {
                var req = HttpWebRequest.Create("http://www.nationalgeographic.com/photography/photo-of-the-day/");
                req.Method = "GET";

                string source;
                using (var reader = new StreamReader(req.GetResponse().GetResponseStream()))
                    source = reader.ReadToEnd();

                string dataFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                string appFolder = Path.Combine(dataFolder, folderName);

                if (!Directory.Exists(appFolder))
                    Directory.CreateDirectory(appFolder);

                ImageInfo oImageInfo = ParseImage(source);

                if (oImageInfo != null)
                {
                    string finalPath = appFolder + "\\" + oImageInfo.Name;

                    SaveImage(oImageInfo.Url, finalPath);

                    SetWallpaper(finalPath);
                }
            }
            catch
            {
            }
        }

        private static ImageInfo ParseImage(string source)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(source);

            var nodesUrl = doc.DocumentNode.SelectNodes("//meta[@property='og:image']");
            string url = nodesUrl == null ? string.Empty : nodesUrl.ToList().ConvertAll(r => r.Attributes.ToList().ConvertAll(i => i.Value)).SelectMany(j => j).Where(x => x.Contains("http")).FirstOrDefault();

            var nodesDate = doc.DocumentNode.SelectNodes("//meta[@property='gsa_publish_date']");
            string date = nodesDate == null ? string.Empty : nodesDate.ToList().ConvertAll(r => r.Attributes.ToList().ConvertAll(i => i.Value)).SelectMany(j => j).Where(x => x.Contains("-")).FirstOrDefault();

            if (string.IsNullOrEmpty(url))
                return null;
            else
            {
                ImageInfo oImageInfo = new ImageInfo();
                oImageInfo.Name = (string.IsNullOrEmpty(date) ? DateTime.Now.ToString("yyyyMMdd") : date.Replace("-", "")) + ".jpg";
                oImageInfo.Url = url;

                return oImageInfo;
            }
        }

        private static void SaveImage(string url, string path)
        {
            var req = HttpWebRequest.Create(url);
            req.Method = "GET";

            var stream = req.GetResponse().GetResponseStream();

            byte[] content;
            using (var br = new BinaryReader(stream))
                content = br.ReadBytes(500000);

            var fs = new FileStream(path, FileMode.Create);
            using (var bw = new BinaryWriter(fs))
                bw.Write(content);
        }

        private static void SetWallpaper(string path)
        {
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE);
        }
    }
}
